#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# @Time    : 2025/9/28 13:40
# @Author  : WXY
# @File    : History.py
# @PROJECT_NAME: youtubedown_gui
# @PRODUCT_NAME: PyCharm
# -------------------------------------------------------------------------------

import sys
import os

from PySide6.QtGui import QColor
from PySide6.QtWidgets import QMainWindow, QApplication, QDialog, QMessageBox
from PySide6.QtCore import Qt

# 添加py_gui目录到路径
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'py_gui'))

from py_gui.history_ui import Ui_history
from LoggerManager import logger_manager
from utils import setup_window_icon, setup_window_title, TABLE_SCROLLBAR_STYLE, show_confirm, show_info
from HistoryManager import history_manager


class HistoryWindow(QMainWindow):
    """历史记录窗口"""

    def __init__(self, parent=None):
        super().__init__(parent)

        # 设置UI
        self.ui = Ui_history()
        self.ui.setupUi(self)
        # 禁用最大化按钮，只保留最小化和关闭按钮
        self.setWindowFlags(
            Qt.WindowType.Window |
            Qt.WindowType.WindowMinimizeButtonHint |
            Qt.WindowType.WindowCloseButtonHint
        )
        # self.setWindowFlags(Qt.WindowType.Window)
        # 设置窗口属性
        # self.setWindowTitle("YouTube 视频下载器")
        setup_window_icon(self)
        setup_window_title(self)

        # 确保窗口不会置顶，设置为普通窗口
        # 设置为普通窗口（非置顶）
        # self.setWindowFlags(Qt.WindowType.Window)
        # self.setWindowFlags(Qt.WindowType.Window | Qt.WindowType.CustomizeWindowHint)
        # # 设置窗口为模态对话框
        # if parent:
        #     self.setWindowModality(Qt.WindowModality.ApplicationModal)
        # 连接信号槽
        self.setup_connections()
        # 初始化数据
        self.init_data()
        logger_manager.info("历史记录窗口初始化完成", "history")

    def setup_connections(self):
        """设置信号槽连接"""
        try:
            # 关闭按钮
            self.ui.btn_close.clicked.connect(self.close)

            # 刷新按钮
            self.ui.btn_refresh.clicked.connect(self.refresh_data)

            # 清空按钮
            self.ui.btn_clear.clicked.connect(self.clear_history)

            # 查询按钮
            self.ui.btn_ok.clicked.connect(self.query_history)

            # 搜索框
            self.ui.searchLineEdit.textChanged.connect(self.filter_data)

            # 状态筛选
            self.ui.statusComboBox.currentTextChanged.connect(self.filter_data)

            logger_manager.debug("历史记录窗口信号槽连接完成", "history")

        except Exception as e:
            logger_manager.error(f"历史记录窗口信号槽连接失败: {e}", "history")

    # 填充数据
    def init_data(self):
        """初始化数据"""
        try:
            # 设置表格列宽
            self.ui.historyTableWidget.setColumnWidth(0, 180)  # URL地址
            self.ui.historyTableWidget.setColumnWidth(1, 100)  # 开始时间
            self.ui.historyTableWidget.setColumnWidth(2, 80)  # 下载状态
            self.ui.historyTableWidget.setColumnWidth(3, 100)  # 文件名称
            self.ui.historyTableWidget.setColumnWidth(4, 100)  # 存储路径
            self.ui.historyTableWidget.setColumnWidth(5, 150)  # 操作
            # 设置表格行高
            self.ui.historyTableWidget.verticalHeader().setDefaultSectionSize(60)

            # 设置表格样式, 行的交替颜色
            self.ui.historyTableWidget.setStyleSheet(
                "QTableWidget {"
                "    background-color: rgba(255, 255, 255, 0.1);"
                "    border: 1px solid rgba(255, 255, 255, 0.3);"
                "    border-radius: 8px;"
                "    color: white;"
                "    gridline-color: rgba(255, 255, 255, 0.2);"
                "    selection-background-color: rgba(76, 161, 175, 0.3);"
                "    font-size: 12px;"
                "    alternate-background-color: rgba(255, 255, 255, 0.05);"  # 交替行颜色
                "}"
                "QTableWidget::item {"
                "    padding: 8px;"
                "    border-bottom: 1px solid rgba(255, 255, 255, 0.1);"
                "    background-color: transparent;"  # 确保单元格背景透明
                "}"
                "QTableWidget::item:selected {"
                "    background-color: rgba(76, 161, 175, 0.4);"
                "    color: white;"
                "}"
                "QTableWidget::item:hover {"
                "    background-color: rgba(255, 255, 255, 0.1);"
                "}"
                "QHeaderView::section {"
                "    background-color: rgba(76, 161, 175, 0.8);"
                "    color: white;"
                "    padding: 10px;"
                "    border: none;"
                "    font-weight: bold;"
                "    font-size: 13px;"
                "}"
                "QHeaderView::section:hover {"
                "    background-color: rgba(76, 161, 175, 1.0);"
                "}"
                "QScrollBar:vertical {"
                "    background-color: rgba(255, 255, 255, 0.1);"
                "    width: 12px;"
                "    border-radius: 6px;"
                "}"
                "QScrollBar::handle:vertical {"
                "    background-color: rgba(76, 161, 175, 0.8);"
                "    border-radius: 6px;"
                "    min-height: 20px;"
                "}"
                "QScrollBar::handle:vertical:hover {"
                "    background-color: rgba(76, 161, 175, 1.0);"
                "}"
                "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {"
                "    border: none;"
                "    background: none;"
                "}"
            )

            # 显示行号
            self.ui.historyTableWidget.verticalHeader().setVisible(True)

            # 设置表格滚动条样式
            self.ui.historyTableWidget.setStyleSheet(TABLE_SCROLLBAR_STYLE)
            # 加载历史数据
            self.load_history_data()

            logger_manager.debug("历史记录数据初始化完成", "history")

        except Exception as e:
            logger_manager.error(f"历史记录数据初始化失败: {e}", "history")

    # 加载历史数据
    def load_history_data(self):
        """加载历史数据"""
        try:
            # 从内存中加载历史数据，不从文件加载
            self.ui.historyTableWidget.setRowCount(0)

            # 从历史记录管理器获取数据
            records = history_manager.get_all_records()

            # 按时间倒序排列（最新的在前面）
            records.sort(key=lambda x: x.download_time, reverse=True)

            # 填充表格
            for record in records:
                self.add_record_to_table(record)

            self.update_total_count()

            logger_manager.debug(f"从内存加载了 {len(records)} 条历史记录", "history")

        except Exception as e:
            logger_manager.error(f"历史记录数据加载失败: {e}", "history")

    def add_record_to_table(self, record):
        """将记录添加到表格中"""
        try:
            from PySide6.QtWidgets import QTableWidgetItem
            from PySide6.QtGui import QColor

            row = self.ui.historyTableWidget.rowCount()
            self.ui.historyTableWidget.insertRow(row)

            # 状态颜色映射
            status_colors = {
                "下载完成": QColor(76, 175, 80),  # 绿色
                "下载失败": QColor(244, 67, 54),  # 红色
                "下载中": QColor(255, 193, 7),  # 黄色
                "等待下载": QColor(156, 39, 176),  # 紫色
                "暂停": QColor(96, 125, 139),  # 灰色
                "重新下载中": QColor(255, 193, 7)  # 黄色
            }

            # 设置URL列
            url_item = QTableWidgetItem(record.url)
            url_item.setToolTip(record.url)
            self.ui.historyTableWidget.setItem(row, 0, url_item)

            # 设置时间列
            time_item = QTableWidgetItem(record.download_time)
            time_item.setToolTip(record.download_time)
            self.ui.historyTableWidget.setItem(row, 1, time_item)

            # 设置状态列
            status_item = QTableWidgetItem(record.status)
            status_color = status_colors.get(record.status, QColor(255, 255, 255))
            status_item.setBackground(QColor(status_color.red(), status_color.green(), status_color.blue(), 50))
            status_item.setForeground(status_color)

            # 格式化分辨率限制显示
            resolution_text = "无限制" if not record.limit_resolution else f"{record.limit_resolution}p及以上"

            status_item.setToolTip(
                f"{record.status}\n分辨率限制: {resolution_text}\n仅MP4: {'是' if record.mp4_only else '否'}")
            self.ui.historyTableWidget.setItem(row, 2, status_item)

            # 设置文件名列
            file_item = QTableWidgetItem(record.title)
            file_item.setToolTip(record.title)
            self.ui.historyTableWidget.setItem(row, 3, file_item)

            # 设置路径列
            path_item = QTableWidgetItem(record.download_path)
            path_item.setToolTip(record.download_path)
            self.ui.historyTableWidget.setItem(row, 4, path_item)

            # 添加操作按钮
            self.add_operation_buttons(row)

        except Exception as e:
            logger_manager.error(f"添加记录到表格失败: {e}", "history")

    def refresh_data(self):
        """刷新数据"""
        try:
            logger_manager.info("刷新历史记录数据", "history")

            # 清空表格内容
            self.ui.historyTableWidget.setRowCount(0)

            # 从内存重新加载数据
            self.load_history_data()

        except Exception as e:
            logger_manager.error(f"刷新历史记录数据失败: {e}", "history")

    def clear_history(self):
        """清空历史记录"""
        try:
            # TODO: 实现清空历史记录的确认对话框和逻辑
            logger_manager.info("清空历史记录功能开发中", "history")

        except Exception as e:
            logger_manager.error(f"清空历史记录失败: {e}", "history")

    def query_history(self):
        """导出历史记录"""
        try:
            # TODO: 实现导出历史记录功能
            logger_manager.info("导出历史记录功能开发中", "history")

        except Exception as e:
            logger_manager.error(f"导出历史记录失败: {e}", "history")

    def filter_data(self):
        """筛选数据"""
        try:
            # TODO: 实现数据筛选逻辑
            search_text = self.ui.searchLineEdit.text()
            status_filter = self.ui.statusComboBox.currentText()

            logger_manager.debug(f"筛选历史记录: 搜索='{search_text}', 状态='{status_filter}'", "history")

        except Exception as e:
            logger_manager.error(f"筛选历史记录失败: {e}", "history")

    def update_total_count(self):
        """更新总计数"""
        try:
            row_count = self.ui.historyTableWidget.rowCount()
            self.ui.totalLabel.setText(f"总计: {row_count} 条记录")

        except Exception as e:
            logger_manager.error(f"更新总计数失败: {e}", "history")

    def closeEvent(self, event):
        """窗口关闭事件"""
        try:
            logger_manager.info("关闭历史记录窗口", "history")

            # 清空表格内容
            self.ui.historyTableWidget.setRowCount(0)

            # 保存历史记录到文件
            history_manager.save_to_file()

            event.accept()

        except Exception as e:
            logger_manager.error(f"关闭历史记录窗口失败: {e}", "history")
            event.accept()

    def add_operation_buttons(self, row):
        """添加操作按钮"""
        try:
            from PySide6.QtWidgets import QWidget, QHBoxLayout, QPushButton

            # 创建操作按钮容器
            operation_widget = QWidget()
            operation_widget.setFixedHeight(50)
            layout = QHBoxLayout(operation_widget)
            layout.setContentsMargins(5, 10, 5, 10)
            layout.setSpacing(8)

            # 创建删除按钮
            delete_btn = QPushButton("删除")
            delete_btn.setObjectName(f"deleteBtn_{row}")
            delete_btn.setFixedSize(50, 32)
            delete_btn.setToolTip("删除这条下载记录")
            delete_btn.setStyleSheet("""
                QPushButton {
                    background-color: #f44336;
                    color: white;
                    border: none;
                    padding: 6px 8px;
                    border-radius: 4px;
                    font-size: 11px;
                    font-weight: bold;
                }
                QPushButton:hover {
                    background-color: #d32f2f;
                }
                QPushButton:pressed {
                    background-color: #b71c1c;
                }
            """)

            # 创建重新下载按钮
            redownload_btn = QPushButton("重新下载")
            redownload_btn.setObjectName(f"redownloadBtn_{row}")
            redownload_btn.setFixedSize(75, 32)
            redownload_btn.setToolTip("重新下载这个视频")
            redownload_btn.setStyleSheet("""
                QPushButton {
                    background-color: #2196f3;
                    color: white;
                    border: none;
                    padding: 6px 8px;
                    border-radius: 4px;
                    font-size: 11px;
                    font-weight: bold;
                }
                QPushButton:hover {
                    background-color: #1976d2;
                }
                QPushButton:pressed {
                    background-color: #0d47a1;
                }
            """)

            # 连接信号槽
            delete_btn.clicked.connect(lambda: self.on_delete_record(row))
            redownload_btn.clicked.connect(lambda: self.on_redownload(row))

            # 添加按钮到布局
            layout.addWidget(delete_btn)
            layout.addWidget(redownload_btn)
            layout.addStretch()  # 添加弹性空间

            # 设置操作列的widget
            self.ui.historyTableWidget.setCellWidget(row, 5, operation_widget)

        except Exception as e:
            logger_manager.error(f"添加操作按钮失败: {e}", "history")

    def on_delete_record(self, row):
        """删除记录"""
        try:

            # 确认删除
            reply = show_confirm(
                self,
                "确认删除",
                "确定要删除这条下载记录吗？"
            )

            if reply == QMessageBox.StandardButton.Yes:
                # 获取URL用于从历史记录管理器中删除
                url_item = self.ui.historyTableWidget.item(row, 0)
                if url_item:
                    url = url_item.text()
                    # 从历史记录管理器中删除
                    history_manager.remove_record(url)

                # 删除表格行
                self.ui.historyTableWidget.removeRow(row)

                # 更新总计标签
                self.update_total_count()

                show_info(self, "删除成功", "记录已删除！")
                logger_manager.info(f"删除了第{row}行记录", "history")

        except Exception as e:
            logger_manager.error(f"删除记录失败: {e}", "history")

    # 重新下载
    def on_redownload(self, row):
        """重新下载"""
        try:
            # 首先从UI表格获取URL（作为查找依据）
            url_item = self.ui.historyTableWidget.item(row, 0)
            if not url_item:
                logger_manager.error("无法获取URL信息", "history")
                return

            url = url_item.text()

            # 通过URL在内存中查找对应的 HistoryRecord 对象
            records = history_manager.get_all_records()
            record = None
            for r in records:
                if r.url == url:
                    record = r
                    break

            # 检查是否找到对应的记录
            if record is None:
                logger_manager.error(f"在内存中未找到URL对应的记录: {url}", "history")
                show_info(
                    self,
                    "错误",
                    "未找到对应的历史记录，请刷新后重试"
                )
                return

            # 弹出确认对话框
            reply = show_confirm(
                self,
                "确认重新下载",
                f"确定要重新下载以下视频吗？\n\n{record.url}\n\n标题: {record.title}"
            )

            # 如果用户点击了"否"，直接返回
            if reply != QMessageBox.StandardButton.Yes:
                return

            # 检查主窗口是否存在且有下载任务在进行
            if self.parent() and hasattr(self.parent(), 'is_downloading'):
                if self.parent().is_downloading:
                    # 如果有任务在下载，显示提示
                    show_info(
                        self,
                        "提示",
                        "当前已有任务在下载中, 本项目每次只能下载一个文件，请稍后"
                    )
                    return

            # 更新状态为"重新下载中"（同时更新内存和UI）
            history_manager.update_record_status(record.url, "重新下载中")

            # 同步更新UI显示
            status_item = self.ui.historyTableWidget.item(row, 2)
            if status_item:
                status_item.setText("重新下载中")
                status_item.setBackground(QColor(255, 193, 7, 50))  # 黄色背景
                status_item.setForeground(QColor(255, 193, 7))  # 黄色文字
                status_item.setToolTip("重新下载中")

            # 将任务发送到主窗口
            if self.parent() and hasattr(self.parent(), 'ui'):
                # 使用 HistoryRecord 对象中的数据
                self.parent().ui.le_url.setText(record.url)
                self.parent().ui.le_download_path.setText(record.download_path)

                # 设置分辨率和格式选项
                # 设置分辨率选择 (comboBox)
                if record.limit_resolution:
                    # 将数据库中的分辨率值转换为UI显示格式
                    resolution_text = f"{record.limit_resolution}P"
                    index = self.parent().ui.comboBox.findText(resolution_text)
                    if index >= 0:
                        self.parent().ui.comboBox.setCurrentIndex(index)
                        logger_manager.info(f"已设置分辨率为: {resolution_text}", "history")
                    else:
                        # 如果找不到对应的分辨率，设置为不限制
                        index = self.parent().ui.comboBox.findText("不限制")
                        if index >= 0:
                            self.parent().ui.comboBox.setCurrentIndex(index)
                        logger_manager.warning(f"未找到分辨率选项 {resolution_text}，已设置为不限制", "history")
                else:
                    # 设置为不限制
                    index = self.parent().ui.comboBox.findText("不限制")
                    if index >= 0:
                        self.parent().ui.comboBox.setCurrentIndex(index)
                        logger_manager.info("已设置分辨率为: 不限制", "history")

                # 设置MP4格式选择 (comboBox_2)
                mp4_text = "是" if record.mp4_only else "否"
                index = self.parent().ui.comboBox_2.findText(mp4_text)
                if index >= 0:
                    self.parent().ui.comboBox_2.setCurrentIndex(index)
                    logger_manager.info(f"已设置MP4格式为: {mp4_text}", "history")

                # 这样下载进度信号才能正确处理
                self.parent().current_download_url = record.url

                # 先切换到主窗口，确保用户能看到下载进度
                self.parent().raise_()
                self.parent().activateWindow()

                # 调用主窗口的下载方法
                self.parent().start_download()

                logger_manager.info(f"已将重新下载任务发送到主窗口: {record.url}", "history")

                # 开始下载后关闭当前窗体
                self.close()

            else:
                logger_manager.error("无法访问主窗口，重新下载失败", "history")
                show_info(
                    self,
                    "错误",
                    "无法访问主窗口，重新下载失败"
                )

        except Exception as e:
            logger_manager.error(f"重新下载失败: {e}", "history")
            show_info(
                self,
                "错误",
                f"重新下载失败: {e}"
            )

if __name__ == "__main__":
    # 测试代码
    app = QApplication(sys.argv)
    window = HistoryWindow()
    window.show()
    sys.exit(app.exec())
